package com.motiv.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.DialogFragment;
import android.widget.EditText;

import com.motiv.application.MotivApplication;
import com.motiv.entities.Goal;
import com.motiv.tools.GoalDbHelper;

/**
 * Created by jdr on 27/08/13.
 */
public class CreateGoalDialog extends DialogFragment {
    private String TAG = this.getClass().getSimpleName();
    private String mParentId;
    private Goal mGoal;
    private DialogInterface.OnDismissListener mDismissListener;
    private EditText mInput;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        Bundle args = getArguments();
        if (args != null)
            mParentId = args.getString(MotivApplication.KEY_GOAL_ID);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle("Create New Goal")
                .setMessage("Enter Goal Name");

        // Set an EditText view to get user input
        mInput = new EditText(getActivity());
        builder.setView(mInput)
                .setPositiveButton("Ok", getOnClickListener());

        return builder.create();
    }

    /**
     * Gets text from EditText in dialog, and creates a new goal using that text as a name.
     * If a parent was supplied as an argument to the dialog, then appropriate relationships are
     * set (which requires the child's new ID retrieved from the DB).
     *
     * @return
     */
    public DialogInterface.OnClickListener getOnClickListener() {
        return new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                mGoal = new Goal(mInput.getText().toString());

                //insert child and get id
                String childId = getActivity().getContentResolver().insert(
                            MotivApplication.URI_GOALS, GoalDbHelper.getCV(mGoal))
                            .getLastPathSegment(); //get child id

                //add new relationship
                getActivity().getContentResolver().insert(
                        MotivApplication.URI_FAMILY,
                        GoalDbHelper.getCV(mParentId, childId));
            }
        };
    }
}
